<template>
  <n-input :disabled="disabled" v-model:value="value as string" :placeholder="'请输入' + label" />
  <c-button :disabled="disabled" @click="selectFolder()" iconName="FolderRound" quaternary type='primary'></c-button>
</template>

<script setup lang='ts'>
import { DialogFilter } from '@tauri-apps/api/dialog';
import localforage from 'localforage';
const { disabled, label, defaultPath, filters, prop } = defineProps<{
  disabled: boolean | undefined,
  label: string,
  defaultPath: string | undefined,
  filters: DialogFilter[] | undefined,
  prop: string
}>()
const value = defineModel<string | Error | string[] | null>()
const selectFolder = async () => {
  if (Tauri.isTauri()) {
    const path = await Tauri.dialogOpen({
      title: "选择文件夹",
      defaultPath,
      filters,
      directory: true,
      multiple: false,
    })
    if (path) {
      value.value = path
    }
  } else {
    const handler: FileSystemDirectoryHandle = await window.showDirectoryPicker({
      mode: 'readwrite',
      startIn: defaultPath
    })
    value.value = handler.name
    const DirectoryHandlerMap = await localforage.getItem('DirectoryHandlerMap') as Record<string, FileSystemDirectoryHandle>
    if (DirectoryHandlerMap) {
      DirectoryHandlerMap[prop] = handler
      await localforage.setItem('DirectoryHandlerMap', DirectoryHandlerMap)
    } else {
      await localforage.setItem('DirectoryHandlerMap', { [prop]: handler })
    }
    value.value = handler.name
  }
}
</script>